package com.appengine.paranoid_android.lost;

import android.app.Activity;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Window;
import android.widget.TextView;

public class LockScreenUpdater extends Activity {
  private static final boolean DEBUG = false;
  private static final String TAG = "Info.KeyguardDisabler";

  protected static final int MSG_DISABLE_KEYGUARD = 1;
  protected static final int MSG_REENABLE_KEYGUARD = 2;

  private KeyguardManager mKeyguardManager;
  private KeyguardLock mKeyguardLock;
  private Handler mHandler;
  private BroadcastReceiver mReceiver;

  class ScreenOnReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
      if (DEBUG) Log.d(TAG, "Screen is on.");
      // Immediately reenable keyguard and finish. The user just saw us. :o)
      doReenableKeyguard();
    }
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    if (DEBUG) Log.v(TAG, "onCreate() called");

    mKeyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
    // Disable keyguard as early as possible.
    doDisableKeyguard();

    // Will immediately reenable the keyguard and finish the activity when the screen turns on.
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_SCREEN_ON);
    registerReceiver(mReceiver = new ScreenOnReceiver(), filter);

    mHandler = new Handler() {
      @Override
      public void handleMessage(Message msg) {
        switch (msg.what) {
          case MSG_DISABLE_KEYGUARD:
            doDisableKeyguard();
            break;
          case MSG_REENABLE_KEYGUARD:
            doReenableKeyguard();
            break;
        }
      }
    };

    // If this activity somehow becomes visible to the user, it would better not display anything.
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    TextView tv = new TextView(this) {
      @Override
      public void draw(Canvas canvas) {
        if (DEBUG) Log.v(TAG, "draw() called");
        super.draw(canvas);
        // Seems to be the last place that gets touched when the activity gets created/displayed.
        // Trigger the delayed keyguard reenabling.
        reenableKeyguardDelayed();
        if (DEBUG) Log.v(TAG, "draw() done");
      }
    };
    // Need to set this to something or the window contents don't get rendered (and the title bar is left visible).
    tv.setText(" ");
    setContentView(tv);

    super.onCreate(savedInstanceState);
    if (DEBUG) Log.v(TAG, "onCreate() done");
  }

  @Override
  public void onWindowFocusChanged(boolean hasFocus) {
    if (!hasFocus) {
      // Safety net: when losing focus, make sure the keyguard is immediately reenabled.
      doReenableKeyguard();
    }
  }

  @Override
  protected void onStop() {
    // Safety net: when stopped, make sure the keyguard is immediately reenabled.
    doReenableKeyguard();
    super.onStop();
  }

  protected void disableKeyguard() {
    mHandler.sendMessage(mHandler.obtainMessage(MSG_DISABLE_KEYGUARD));
  }

  protected void doDisableKeyguard() {
    if (mKeyguardLock == null) {
      mKeyguardLock = mKeyguardManager.newKeyguardLock(TAG);
      mKeyguardLock.disableKeyguard();
      if (DEBUG) Log.d(TAG, "Disabled keyguard.");
    }
  }

  protected void reenableKeyguardDelayed() {
    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_REENABLE_KEYGUARD), 3000);
  }

  protected void doReenableKeyguard() {
    if (mReceiver != null) {
      unregisterReceiver(mReceiver);
      mReceiver = null;
    }
    if (mKeyguardLock != null) {
      KeyguardManager.KeyguardLock temp = mKeyguardLock;
      mKeyguardLock = null;
      if (DEBUG) Log.d(TAG, "Reenabling keyguard.");
      temp.reenableKeyguard();
      if (DEBUG) Log.d(TAG, "Reenabled keyguard.");
    }
    // Once the keyguard has been reenabled, get out of the way as quickly as possible.
    if (!isFinishing()) {
      if (DEBUG) Log.d(TAG, "Calling finish()...");
      finish();
    }
  }
}
